import WebSocketManager from './websocket.js';

// 消息类型常量定义 - 根据2024最新版WebSocket通讯协议文档
const MessageType = {
    // 客户端 → 服务端消息类型
    MessageTypeClientHeartbeat : 0, //心跳
    MessageTypeClientLogin : 1000, //登录
    MessageTypeClientCubeMove : 1001, //魔方转动
    MessageTypeClientCubeAngle : 1002, //陀螺仪数据
    MessageTypeClientCubeState : 1003, //魔方状态
    MessageTypeClientRoomStatusChange : 1010,//改变房间状态
    MessageTypeClientRoomSeatStatusChange : 1020,//改变房间席位状态
    MessageTypeClientRoomSeatOwerStatusChange : 1030,//席位拥有者状态
    
    /**
     服务端协议
    */
    MessageTypeServerHeartbeat : 1, //心跳回复
    MessageTypeServerLoginResp : 2000, //登录结果

    // 比赛信息推送
    MessageTypeServerPlayerCubeMove :2001, //选手魔方转动
    // 比赛信息推送
    MessageTypeServerPlayerCubeAngle : 2002, //选手陀螺仪
    // 比赛信息推送
    MessageTypeServerPlayerCubeState : 2003, //选手魔方操作

    // 房间状态变更
    //    PLAYER_JOIN(1),        // 玩家加入
    //    PLAYER_LEAVE(2),       // 玩家离开
    //    ALL_READY(3),          // 所有席位准备就绪
    //    START_COUNTDOWN(4),    // 开始倒计时
    //    START_GAME(5),         // 开始比赛
    //
    //    PAUSE_GAME(6),         // 暂停比赛
    //    RESUME_GAME(7),        // 恢复比赛
    //    END_GAME(8),           // 结束比赛
    //    CANCEL_GAME(9),        // 取消比赛
    //    RESTART_GAME(10),      // 重新比赛
    //    ERROR_OCCURRED(99);      // 发生异常
    MessageTypeServerRoomStatusChange : 2010, //
    // 房间席位状态变更
    //    JOIN(0),               // 加入
    //    PREPARE(1),            // 准备
    //    START_PREPARE(2),      // 开始赛前准备
    //    PLAN_STRATEGY(3),      // 策略规划
    //    START_GAME(4),         // 开始比赛
    //    END_GAME(5),           // 结束比赛
    //    LEAVE(6),              // 离开
    //    RESTART_GAME(8),       // 重新比赛
    //    ERROR_OCCURRED(7);      // 发生异常
    MessageTypeServerRoomSeatStatusChange : 2020, //


    MessageTypeServerRoomSeatOwerStatusChange : 2030, //
};

class SocketServerAdapter {
    constructor() {
        this.wsManager = new WebSocketManager();
        this.userId = null;
        this.currentRoomId = null;
        this.eventCallbacks = new Map();
        this.setupMessageHandlers();
    }

    // 设置消息处理器
    setupMessageHandlers() {
        // 连接状态监听
        this.wsManager.on('connection_status', (data) => {
            console.log('连接状态变更:', data);
            this.emit('connection_status', data);
        });

        // 连接错误监听
        this.wsManager.on('connection_error', (error) => {
            console.error('连接错误:', error);
            this.emit('connection_error', error);
        });

        // 重连失败监听
        this.wsManager.on('reconnect_failed', (data) => {
            console.error('重连失败:', data);
            this.emit('reconnect_failed', data);
        });

        // 通用消息处理器 - 根据messageType分发消息
        this.wsManager.on('message', (data) => {
            this.handleServerMessage(data);
        });
    }

    // 处理服务端消息
    handleServerMessage(data) {
        const messageType = parseInt(data.messageType);
        
        console.log('处理服务端消息, messageType:', messageType, '完整数据:', data);
        
        switch (messageType) {
            case MessageType.MessageTypeServerHeartbeat:
                console.log('收到心跳响应:', data);
                this.emit('heartbeat_response', data);
                break;
                
            case MessageType.MessageTypeServerRoomStatusChange:
                console.log('房间状态变更通知:', data);
                this.emit('room_status_change', data);
                break;
                
            case MessageType.MessageTypeServerRoomSeatStatusChange:
                console.log('房间席位状态变更通知:', data);
                this.emit('room_seat_status_change', data);
                break;
                
            case MessageType.MessageTypeServerRoomSeatOwerStatusChange:
                console.log('席位拥有者状态变更通知:', data);
                this.emit('room_seat_owner_status_change', data);
                break;
                
            case MessageType.MessageTypeServerPlayerCubeMove:
                console.log('魔方转动广播:', data);
                // 解析新的魔方转动广播格式
                const cubeMoveData = {
                    messageType: data.messageType,
                    code: data.code,
                    move: data.move,           // 转动动作 (如 "R", "L", "U", "D", "F", "B")
                    interval: data.interval,   // 转动间隔时间
                    step: data.step,           // 转动步数
                    rotate: data.rotate,       // 转动角度
                    modify: data.modify        // 修改标志
                };
                console.log('解析后的魔方转动数据:', cubeMoveData);
                this.emit('player_cube_move', cubeMoveData);
                break;
                
            case MessageType.MessageTypeServerPlayerCubeAngle:
                console.log('陀螺仪数据广播:', data);
                this.emit('player_cube_angle', data);
                break;
                
            case MessageType.MessageTypeServerPlayerCubeState:
                console.log('魔方状态广播:', data);
                this.emit('player_cube_state', data);
                break;
                
            default:
                console.log('未知消息类型:', messageType, '数据:', data);
                this.emit('unknown_message', data);
                break;
        }
    }

    // 连接服务器
    async connect(url) {
        try {
            if (url) {
                this.wsManager.setServerUrl(url);
            }
            await this.wsManager.connect();
            console.log('WebSocket连接成功');
            return true;
        } catch (error) {
            console.error('WebSocket连接失败:', error);
            return false;
        }
    }

    // 断开连接
    disconnect() {
        this.wsManager.disconnect();
    }

    // 用户登录
    login(token) {
        const loginMessage = {
            messageType: MessageType.MessageTypeClientLogin,
            token: token
        };
        console.log('发送登录消息:', loginMessage);
        return this.wsManager.send(loginMessage);
    }

    // 发送心跳
    sendHeartbeat(roomId = this.currentRoomId) {
        const heartbeat = {
            messageType: MessageType.MessageTypeClientHeartbeat,
            timestamp: Date.now(),
            roomId: roomId || ""
        };
        console.log('发送心跳消息:', heartbeat);
        return this.wsManager.send(heartbeat);
    }

    // 房间状态变更
    sendRoomStatusChange(roomId, event) {
        const roomStatusMessage = {
            messageType: MessageType.MessageTypeClientRoomStatusChange,
            roomId: roomId,
            event: event
        };
        console.log('发送房间状态变更消息:', roomStatusMessage);
        return this.wsManager.send(roomStatusMessage);
    }

    // 房间席位状态变更
    sendRoomSeatStatusChange(seatId, event, roomId) {
        const seatStatusMessage = {
            messageType: MessageType.MessageTypeClientRoomSeatStatusChange,
            seatId: seatId,
            event: event,
            roomId: roomId
        };
        console.log('发送房间席位状态变更消息:', seatStatusMessage);
        return this.wsManager.send(seatStatusMessage);
    }

    // 席位拥有者状态变更（成绩上报）
    sendRoomSeatOwnerStatusChange(userId, steps, rotate, tps, smooth, currentTPS, progress) {
        const ownerStatusMessage = {
            messageType: MessageType.MessageTypeClientRoomSeatOwerStatusChange,
            userId: userId,
            steps: steps,
            rotate: rotate,
            tps: tps,
            smooth: smooth,
            currentTPS: currentTPS,
            progress: progress
        };
        console.log('发送席位拥有者状态变更消息:', ownerStatusMessage);
        return this.wsManager.send(ownerStatusMessage);
    }

    // 发送魔方移动
    sendCubeMove(move, interval, step, rotate, modify) {
        const cubeMoveMessage = {
            messageType: MessageType.MessageTypeClientCubeMove,
            move: move,
            interval: interval,
            step: step,
            rotate: rotate,
            modify: modify
        };
        console.log('发送魔方移动消息:', cubeMoveMessage);
        return this.wsManager.send(cubeMoveMessage);
    }

    // 发送魔方角度
    sendCubeAngle(x, y, z) {
        const cubeAngleMessage = {
            messageType: MessageType.MessageTypeClientCubeAngle,
            x: x,
            y: y,
            z: z
        };
        console.log('发送魔方角度消息:', cubeAngleMessage);
        return this.wsManager.send(cubeAngleMessage);
    }

    // 发送魔方状态
    sendCubeState(stateL, upFrontL) {
        const cubeStateMessage = {
            messageType: MessageType.MessageTypeClientCubeState,
            stateL: stateL,
            upFrontL: upFrontL
        };
        console.log('发送魔方状态消息:', cubeStateMessage);
        return this.wsManager.send(cubeStateMessage);
    }

    // 发送自定义消息
    sendCustomMessage(message) {
        console.log('发送自定义消息:', message);
        return this.wsManager.send(message);
    }

    // 发送带重试的消息
    async sendWithRetry(message, maxRetries = 3) {
        try {
            await this.wsManager.sendWithRetry(message, maxRetries);
            return true;
        } catch (error) {
            console.error('消息发送失败:', error);
            return false;
        }
    }

    // 获取连接状态
    getConnectionStatus() {
        return this.wsManager.getConnectionStatus();
    }

    // 订阅自定义事件
    on(event, callback) {
        if (!this.eventCallbacks.has(event)) {
            this.eventCallbacks.set(event, []);
        }
        this.eventCallbacks.get(event).push(callback);
    }

    // 取消订阅
    off(event, callback) {
        if (this.eventCallbacks.has(event)) {
            const callbacks = this.eventCallbacks.get(event);
            const index = callbacks.indexOf(callback);
            if (index > -1) {
                callbacks.splice(index, 1);
            }
        }
    }

    // 触发事件
    emit(event, data) {
        if (this.eventCallbacks.has(event)) {
            const callbacks = this.eventCallbacks.get(event);
            callbacks.forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error('SocketServerAdapter 事件回调执行错误:', error);
                }
            });
        }
    }

    // 清理资源
    destroy() {
        this.wsManager.destroy();
        this.eventCallbacks.clear();
    }

    // 获取消息类型常量
    static getMessageType() {
        return MessageType;
    }
}

export default SocketServerAdapter; 